package com.ihr360.job.core.listener;

import com.ihr360.job.core.ChunkListener;
import com.ihr360.job.core.scope.context.ChunkContext;
import org.springframework.core.Ordered;

import java.util.Iterator;
import java.util.List;

public class CompositeChunkListener implements ChunkListener {
    private OrderedComposite<ChunkListener> listeners = new OrderedComposite<ChunkListener>();

    /**
     * Public setter for the listeners.
     *
     * @param listeners
     */
    public void setListeners(List<? extends ChunkListener> listeners) {
        this.listeners.setItems(listeners);
    }

    /**
     * Register additional listener.
     *
     * @param chunkListener
     */
    public void register(ChunkListener chunkListener) {
        listeners.add(chunkListener);
    }

    /**
     * Call the registered listeners in order, respecting and prioritizing those
     * that implement {@link Ordered}.
     *
     * @see org.springframework.batch.core.ChunkListener#afterChunk(ChunkContext context)
     */
    @Override
    public void afterChunk(ChunkContext context) {
        for (Iterator<ChunkListener> iterator = listeners.iterator(); iterator.hasNext();) {
            ChunkListener listener = iterator.next();
            listener.afterChunk(context);
        }
    }

    /**
     * Call the registered listeners in reverse order.
     *
     * @see org.springframework.batch.core.ChunkListener#beforeChunk(ChunkContext context)
     */
    @Override
    public void beforeChunk(ChunkContext context) {
        for (Iterator<ChunkListener> iterator = listeners.reverse(); iterator.hasNext();) {
            ChunkListener listener = iterator.next();
            listener.beforeChunk(context);
        }
    }

    @Override
    public void afterChunkError(ChunkContext context) {
        for (Iterator<ChunkListener> iterator = listeners.iterator(); iterator.hasNext();) {
            ChunkListener listener = iterator.next();
            listener.afterChunkError(context);
        }
    }
}